package com.itheima.employee.controller;
import com.alibaba.fastjson.JSON;
import com.itheima.common.controller.BaseController;
import com.itheima.common.entity.Result;
import com.itheima.common.entity.ResultCode;
import com.itheima.common.utils.BeanMapUtils;
import com.itheima.common.utils.ExcelExportUtils;
import com.itheima.employee.pojo.*;
import com.itheima.employee.pojo.vo.EmployeeReportVo;
import com.itheima.employee.service.*;
import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JasperFillManager;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author qiankaofei
 * @version 1.0
 * @date 2020/11/16 10:45
 */
@RestController
@RequestMapping("/employees")
@SuppressWarnings(value = "all")
public class EmployeeController extends BaseController {

    @Autowired
    private UserCompanyPersonalService userCompanyPersonalService;

    @Autowired
    private UserCompanyJobsService userCompanyJobsService;

    @Autowired
    private ResignationService resignationService;

    @Autowired
    private TransferPositionService transferPositionService;

    @Autowired
    private PositiveService positiveService;

    @Autowired
    private ArchiveService archiveService;

    /**
     * fegin测试
     */
    @RequestMapping(value = "/json", method = RequestMethod.GET)
    public String findJson(){
        return "邢舒颍!";
    }

    /**
     * 员工个人信息保存
     */
    @RequestMapping(value = "/{id}/personalInfo", method = RequestMethod.PUT)
    public Result savePersonalInfo(@PathVariable(name = "id") String uid, @RequestBody Map map) throws Exception {
        UserCompanyPersonal sourceInfo = BeanMapUtils.mapToBean(map, UserCompanyPersonal.class);
        if (sourceInfo == null) {
            sourceInfo = new UserCompanyPersonal();
        }
        sourceInfo.setUserId(uid);
        sourceInfo.setCompanyId(super.companyId);
        Integer count = userCompanyPersonalService.save(sourceInfo);
        return count>0?new Result(ResultCode.SUCCESS):new Result(ResultCode.FAIL);
    }


    /**
     * 员工个人信息读取
     */
    @RequestMapping(value = "/{id}/personalInfo", method = RequestMethod.GET)
    public Result findPersonalInfo(@PathVariable(name = "id") String uid) throws Exception {
        UserCompanyPersonal info = userCompanyPersonalService.findById(uid);
        if(info == null) {
            info = new UserCompanyPersonal();
            info.setUserId(uid);
        }
        return new Result(ResultCode.SUCCESS,info);
    }

    /**
     * 提供给社保微服务调用  返回json串
     *
     */
    @RequestMapping(value = "/personalInfoToJson/{id}", method = RequestMethod.GET)
    public UserCompanyPersonal findPersonalInfoToJson(@PathVariable(name = "id") String id) throws Exception {
        UserCompanyPersonal info = userCompanyPersonalService.findById(id);
        if(info == null) {
            info = new UserCompanyPersonal();
            info.setUserId(id);
        }
        return info;
    }

    /**
     * 员工岗位信息保存
     */
    @RequestMapping(value = "/{id}/jobs", method = RequestMethod.PUT)
    public Result saveJobsInfo(@PathVariable(name = "id") String uid, @RequestBody UserCompanyJobs sourceInfo) throws Exception {
        //更新员工岗位信息
        if (sourceInfo == null) {
            sourceInfo = new UserCompanyJobs();
            sourceInfo.setUserId(uid);
            sourceInfo.setCompanyId(super.companyId);
        }
        Integer count = userCompanyJobsService.save(sourceInfo);
        return count>0?new Result(ResultCode.SUCCESS):new Result(ResultCode.FAIL);
    }



    /**
     * 员工岗位信息读取
     */
    @RequestMapping(value = "/{id}/jobs", method = RequestMethod.GET)
    public Result findJobsInfo(@PathVariable(name = "id") String uid) throws Exception {
        UserCompanyJobs info = userCompanyJobsService.findById(super.userId);
        if(info == null) {
            info = new UserCompanyJobs();
            info.setUserId(uid);
            info.setCompanyId(companyId);
        }
        return new Result(ResultCode.SUCCESS,info);
    }

    /**
     * 离职表单保存
     */
    @RequestMapping(value = "/{id}/leave", method = RequestMethod.PUT)
    public Result saveLeave(@PathVariable(name = "id") String uid, @RequestBody EmployeeResignation resignation) throws Exception {
        resignation.setUserId(uid);
        Integer count = resignationService.save(resignation);
        return count>0?new Result(ResultCode.SUCCESS):new Result(ResultCode.FAIL);
    }

    /**
     * 离职表单读取
     */
    @RequestMapping(value = "/{id}/leave", method = RequestMethod.GET)
    public Result findLeave(@PathVariable(name = "id") String uid) throws Exception {
        EmployeeResignation resignation = resignationService.findById(uid);
        if(resignation == null) {
            resignation = new EmployeeResignation();
            resignation.setUserId(uid);
        }
        return new Result(ResultCode.SUCCESS,resignation);
    }

    /**
     * 导入员工
     */
    @RequestMapping(value = "/import", method = RequestMethod.POST)
    public Result importDatas(@RequestParam(name = "file") MultipartFile attachment) throws Exception {
        //TODO...
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * 调岗表单保存
     */
    @RequestMapping(value = "/{id}/transferPosition", method = RequestMethod.PUT)
    public Result saveTransferPosition(@PathVariable(name = "id") String uid, @RequestBody EmployeeTransferPosition transferPosition) throws Exception {
        transferPosition.setUserId(uid);
        Integer count=transferPositionService.save(transferPosition);
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * 调岗表单读取
     */
    @RequestMapping(value = "/{id}/transferPosition", method = RequestMethod.GET)
    public Result findTransferPosition(@PathVariable(name = "id") String uid) throws Exception {
        UserCompanyJobs jobsInfo = userCompanyJobsService.findById(uid);
        if(jobsInfo == null) {
            jobsInfo = new UserCompanyJobs();
            jobsInfo.setUserId(uid);
        }
        return new Result(ResultCode.SUCCESS,jobsInfo);
    }

    /**
     * 转正表单保存
     */
    @RequestMapping(value = "/{id}/positive", method = RequestMethod.PUT)
    public Result savePositive(@PathVariable(name = "id") String uid, @RequestBody EmployeePositive positive) throws Exception {
        Integer count=positiveService.save(positive);
        return count>0?new Result(ResultCode.SUCCESS):new Result(ResultCode.FAIL);
    }

    /**
     * 转正表单读取
     */
    @RequestMapping(value = "/{id}/positive", method = RequestMethod.GET)
    public Result findPositive(@PathVariable(name = "id") String uid) throws Exception {
        EmployeePositive positive = positiveService.findById(uid);
        if(positive == null) {
            positive = new EmployeePositive();
            positive.setUserId(uid);
        }
        return new Result(ResultCode.SUCCESS,positive);
    }

    /**
     * 历史归档详情列表
     */
    @RequestMapping(value = "/archives/{month}", method = RequestMethod.GET)
    public Result archives(@PathVariable(name = "month") String month, @RequestParam(name = "type") Integer type) throws Exception {
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * 归档更新
     */
    @RequestMapping(value = "/archives/{month}", method = RequestMethod.PUT)
    public Result saveArchives(@PathVariable(name = "month") String month) throws Exception {
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * 历史归档列表
     */
    @RequestMapping(value = "/archives", method = RequestMethod.GET)
    public Result findArchives(@RequestParam(name = "pagesize") Integer pagesize, @RequestParam(name = "page") Integer page, @RequestParam(name = "year") String year) throws Exception {
        return new Result(ResultCode.SUCCESS,archiveService.findSearch(year,this.companyId,page,pagesize));
    }

    /**
     * 人事报表导出（普通的导出）
     * 实现思路：
     *  1. 在内存中创建一个Excel工作簿
     *  2. 写入标题行
     *  3. 查询要填入的数据（当月入职的员工信息+离职信息），写入单元格
     *
     *  如果百万条数据导出
     *      只需要将XSSWorkbook 换成SXSSWorkbook即可
     */
    @GetMapping("/export/common/{month}")
    public void export(@PathVariable("month") String month, HttpServletRequest request, HttpServletResponse response)  {
        Workbook workbook=null;
        OutputStream os=null;
        try {
            //标题行
            String[] headers="编号,姓名,手机,最高学历,国家地区,护照号,籍贯,生日,属相,入职时间,离职类型,离职原因,离职时间".split(",");
            //在内存中创建一个Workbook对象
            workbook=new XSSFWorkbook();
            Sheet sheet = workbook.createSheet();
            //创建第一行
            Row row = sheet.createRow(0);
            for(Integer i=0;i<headers.length;i++){
                //创建第一行的每一列的单元格，并往里面填充数据
                Cell cell = row.createCell(i);
                cell.setCellValue(headers[i]);
            }
            //查询要填充的数据
            //List<EmployeeReportVo> employeeReportVoList=userCompanyPersonalService.exportEmPersonal(this.companyId,month);
            List<EmployeeReportVo> employeeReportVoList=userCompanyPersonalService.exportEmPersonal("1","2018-03");
            // 填充正式数据
            Integer rowNum=1;
            for(Integer i=0;i<employeeReportVoList.size();i++){
                row=sheet.createRow(rowNum);
                Cell cell=row.createCell(0);
                //编号
                if(StringUtils.isNotBlank(employeeReportVoList.get(i).getUserId())){
                    cell.setCellValue(employeeReportVoList.get(i).getUserId());
                }else{
                    cell.setCellValue("");
                }
                // 姓名
                cell=row.createCell(1);
                if(StringUtils.isNotBlank(employeeReportVoList.get(i).getUsername())){
                    cell.setCellValue(employeeReportVoList.get(i).getUsername());
                }else{
                    cell.setCellValue("");
                }
                // 手机
                cell=row.createCell(2);
                if(StringUtils.isNotBlank(employeeReportVoList.get(i).getMobile())){
                    cell.setCellValue(employeeReportVoList.get(i).getMobile());
                }else{
                    cell.setCellValue("");
                }
                // 最高学历
                cell=row.createCell(3);
                if(StringUtils.isNotBlank(employeeReportVoList.get(i).getTheHighestDegreeOfEducation())){
                    cell.setCellValue(employeeReportVoList.get(i).getTheHighestDegreeOfEducation());
                }else{
                    cell.setCellValue("");
                }
                // 国家地区
                cell=row.createCell(4);
                if(StringUtils.isNotBlank(employeeReportVoList.get(i).getNationalArea())){
                    cell.setCellValue(employeeReportVoList.get(i).getNationalArea());
                }else{
                    cell.setCellValue("");
                }
                // 护照号
                cell=row.createCell(5);
                if(StringUtils.isNotBlank(employeeReportVoList.get(i).getPassportNo())){
                    cell.setCellValue(employeeReportVoList.get(i).getPassportNo());
                }else{
                    cell.setCellValue("");
                }
                // 籍贯
                cell=row.createCell(6);
                if(StringUtils.isNotBlank(employeeReportVoList.get(i).getNativePlace())){
                    cell.setCellValue(employeeReportVoList.get(i).getNativePlace());
                }else{
                    cell.setCellValue("");
                }
                // 生日
                cell=row.createCell(7);
                if(StringUtils.isNotBlank(employeeReportVoList.get(i).getNativePlace())){
                    cell.setCellValue(employeeReportVoList.get(i).getNativePlace());
                }else{
                    cell.setCellValue("");
                }
                // 属相
                cell=row.createCell(8);
                if(StringUtils.isNotBlank(employeeReportVoList.get(i).getZodiac())){
                    cell.setCellValue(employeeReportVoList.get(i).getZodiac());
                }else{
                    cell.setCellValue("");
                }
                // 入职时间
                cell=row.createCell(9);
                if(StringUtils.isNotBlank(employeeReportVoList.get(i).getTimeOfEntry())){
                    cell.setCellValue(employeeReportVoList.get(i).getTimeOfEntry());
                }else{
                    cell.setCellValue("");
                }
                // 离职类型
                cell=row.createCell(10);
                if(StringUtils.isNotBlank(employeeReportVoList.get(i).getTypeOfTurnover())){
                    cell.setCellValue(employeeReportVoList.get(i).getTypeOfTurnover());
                }else{
                    cell.setCellValue("");
                }
                // 离职原因
                cell=row.createCell(11);
                if(StringUtils.isNotBlank(employeeReportVoList.get(i).getReasonsForLeaving())){
                    cell.setCellValue(employeeReportVoList.get(i).getReasonsForLeaving());
                }else{
                    cell.setCellValue("");
                }
                // 离职时间
                cell=row.createCell(12);
                if(StringUtils.isNotBlank(employeeReportVoList.get(i).getResignationTime())){
                    cell.setCellValue(employeeReportVoList.get(i).getResignationTime());
                }else{
                    cell.setCellValue("");
                }
                rowNum++;
            }

            String fileName= URLEncoder.encode(month+"月人事报表.xlsx","utf-8");
            //将Excel文件以流的形式下载
            response.setContentType("application/vnd.ms-excel-templates");
            response.setCharacterEncoding("utf-8");
            //Content-disposition属性设置成以附件方式进行下载
            response.setHeader("Content-disposition", "attachment;filename="+ fileName);
            os = response.getOutputStream();
            workbook.write(os);
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(workbook!=null){
                try {
                    workbook.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(os!=null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 模板导出
     *      获取文件流方式一：
     *          InputStream fis = this.getClass().getClassLoader().getResourceAsStream("/excel-templates/hr-demo.xlsx");
     *          此种方式支持Window运行环境，Linux运行环境
     *      获取文件流方式二：
     *          Resource resource = new ClassPathResource("excel-templates-templates/hr-demo.xlsx");
     *          FileInputStream fis = new FileInputStream(resource.getFile());
     *          此种方式只支持window环境，不支持Linux环境
     *      生成环境一般都是Linux环境
     *
     */
//    @PostMapping("/export/{month}")
//    public  void exporttemplate(@PathVariable("month") String month,HttpServletRequest request,HttpServletResponse response){
//        InputStream fis=null;
//        Workbook workbook=null;
//        OutputStream os=null;
//        try{
//            fis = this.getClass().getResourceAsStream("/excel-templates/hr-demo.xlsx");
//            workbook=new XSSFWorkbook(fis);
//            //获取第一个工作簿
//            Sheet sheet = workbook.getSheetAt(0);
//            //抽取第三行的公共样式
//            Row row = sheet.getRow(2);
//            CellStyle[] styles=new CellStyle[row.getLastCellNum()];
//            for(Integer i=0;i<row.getLastCellNum();i++){
//                styles[i]=row.getCell(i).getCellStyle();
//            }
//            //从第三行开始填充数据
//            AtomicInteger atomicInteger=new AtomicInteger(2);
//            Cell cell=null;
//            //查询要填充的数据
//            List<EmployeeReportVo> employeeReportVoList = userCompanyPersonalService.exportEmPersonal(this.companyId, month);
//            //List<EmployeeReportVo> employeeReportVoList = userCompanyPersonalService.exportEmPersonal("1", "2018-03");
//            for (EmployeeReportVo employeeReportVo : employeeReportVoList) {
//                row=sheet.createRow(atomicInteger.getAndIncrement());
//                //编号
//                cell=row.createCell(0);
//                if(StringUtils.isNotBlank(employeeReportVo.getUserId())){
//                    cell.setCellValue(employeeReportVo.getUserId());
//                    cell.setCellStyle(styles[0]);
//                }else{
//                    cell.setCellValue("");
//                    cell.setCellStyle(styles[0]);
//                }
//                // 姓名
//                cell=row.createCell(1);
//                if(StringUtils.isNotBlank(employeeReportVo.getUsername())){
//                    cell.setCellValue(employeeReportVo.getUsername());
//                    cell.setCellStyle(styles[1]);
//                }else{
//                    cell.setCellValue("");
//                    cell.setCellStyle(styles[1]);
//                }
//                // 手机
//                cell=row.createCell(2);
//                if(StringUtils.isNotBlank(employeeReportVo.getMobile())){
//                    cell.setCellValue(employeeReportVo.getMobile());
//                    cell.setCellStyle(styles[2]);
//                }else{
//                    cell.setCellValue("");
//                    cell.setCellStyle(styles[2]);
//                }
//                // 最高学历
//                cell=row.createCell(3);
//                if(StringUtils.isNotBlank(employeeReportVo.getTheHighestDegreeOfEducation())){
//                    cell.setCellValue(employeeReportVo.getTheHighestDegreeOfEducation());
//                    cell.setCellStyle(styles[3]);
//                }else{
//                    cell.setCellValue("");
//                    cell.setCellStyle(styles[3]);
//                }
//                // 国家地区
//                cell=row.createCell(4);
//                if(StringUtils.isNotBlank(employeeReportVo.getNationalArea())){
//                    cell.setCellValue(employeeReportVo.getNationalArea());
//                    cell.setCellStyle(styles[4]);
//                }else{
//                    cell.setCellValue("");
//                    cell.setCellStyle(styles[4]);
//                }
//                // 护照号
//                cell=row.createCell(5);
//                if(StringUtils.isNotBlank(employeeReportVo.getPassportNo())){
//                    cell.setCellValue(employeeReportVo.getPassportNo());
//                    cell.setCellStyle(styles[5]);
//                }else{
//                    cell.setCellValue("");
//                    cell.setCellStyle(styles[5]);
//                }
//                // 籍贯
//                cell=row.createCell(6);
//                if(StringUtils.isNotBlank(employeeReportVo.getNativePlace())){
//                    cell.setCellValue(employeeReportVo.getNativePlace());
//                    cell.setCellStyle(styles[6]);
//                }else{
//                    cell.setCellValue("");
//                    cell.setCellStyle(styles[6]);
//                }
//                // 生日
//                cell=row.createCell(7);
//                if(StringUtils.isNotBlank(employeeReportVo.getBirthday())){
//                    cell.setCellValue(employeeReportVo.getBirthday());
//                    cell.setCellStyle(styles[7]);
//                }else{
//                    cell.setCellValue("");
//                    cell.setCellStyle(styles[7]);
//                }
//                // 属相
//                cell=row.createCell(8);
//                if(StringUtils.isNotBlank(employeeReportVo.getZodiac())){
//                    cell.setCellValue(employeeReportVo.getZodiac());
//                    cell.setCellStyle(styles[8]);
//                }else{
//                    cell.setCellValue("");
//                    cell.setCellStyle(styles[8]);
//                }
//                // 入职时间
//                cell=row.createCell(9);
//                if(StringUtils.isNotBlank(employeeReportVo.getTimeOfEntry())){
//                    cell.setCellValue(employeeReportVo.getTimeOfEntry());
//                    cell.setCellStyle(styles[9]);
//                }else{
//                    cell.setCellValue("");
//                    cell.setCellStyle(styles[9]);
//                }
//                // 离职类型
//                cell=row.createCell(10);
//                if(StringUtils.isNotBlank(employeeReportVo.getTypeOfTurnover())){
//                    cell.setCellValue(employeeReportVo.getTypeOfTurnover());
//                    cell.setCellStyle(styles[10]);
//                }else{
//                    cell.setCellValue("");
//                    cell.setCellStyle(styles[10]);
//                }
//                // 离职原因
//                cell=row.createCell(11);
//                if(StringUtils.isNotBlank(employeeReportVo.getReasonsForLeaving())){
//                    cell.setCellValue(employeeReportVo.getReasonsForLeaving());
//                    cell.setCellStyle(styles[11]);
//                }else{
//                    cell.setCellValue("");
//                    cell.setCellStyle(styles[11]);
//                }
//                // 离职时间
//                cell=row.createCell(12);
//                if(StringUtils.isNotBlank(employeeReportVo.getResignationTime())){
//                    cell.setCellValue(employeeReportVo.getResignationTime());
//                    cell.setCellStyle(styles[12]);
//                }else{
//                    cell.setCellValue("");
//                    cell.setCellStyle(styles[12]);
//                }
//            }
//            //以流的形式下载
//            String fileName= URLEncoder.encode(month+"月人事报表.xlsx","utf-8");
//            //将Excel文件以流的形式下载
//            response.setContentType("application/vnd.ms-excel-templates");
//            response.setCharacterEncoding("utf-8");
//            //Content-disposition属性设置成以附件方式进行下载
//            response.setHeader("Content-disposition", "attachment;filename="+ fileName);
//            os = response.getOutputStream();
//            workbook.write(os);
//            os.flush();
//        }catch(Exception e){
//            e.printStackTrace();
//        }finally {
//            if(os!=null){
//                try {
//                    os.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//            if(workbook!=null){
//                try {
//                    workbook.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//            if(os!=null){
//                try {
//                    os.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        }
//
//    }

    /**
     * 模板打印基于注解的方式导出excel
     */
    @PostMapping("/export/{month}")
    public void exportByAnno(@PathVariable("month") String month, HttpServletRequest request,HttpServletResponse response){
        try{
            //模板文件流
            InputStream ins = this.getClass().getResourceAsStream("/excel-template/hr-demo.xlsx");
            //查询要打印的数据
            //List<EmployeeReportVo> employeeReportVoList=userCompanyPersonalService.exportEmPersonal("1","2018-03");
            List<EmployeeReportVo> employeeReportVoList=userCompanyPersonalService.exportEmPersonal(this.companyId,month);
            ExcelExportUtils<EmployeeReportVo> excelExportUtils =new ExcelExportUtils<EmployeeReportVo>(EmployeeReportVo.class,2,2);
            excelExportUtils.export(request,response,month+"月人事报表导出.xlsx",employeeReportVoList,ins);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 打印pdf
     */

    @RequestMapping(value = "/{id}/pdf",method = RequestMethod.GET)
    public void pdf(@PathVariable("id") String id, HttpServletResponse response){
        ServletOutputStream os=null;
        try {
            //引入jasper模板文件
            InputStream ins = this.getClass().getResourceAsStream("/templates/profile.jasper");
            // 构造数据
            //1. 用户详情数据
            Map<String, Object> map1 = BeanMapUtils.beanToMap(userCompanyPersonalService.findById(id));
            //2. 用户岗位数据
            Map<String, Object> map2 = BeanMapUtils.beanToMap(userCompanyJobsService.findById(id));
            //3. 用户头像数据(跨服务调用)
            String staffPhoto="https://itcastly.oss-cn-shanghai.aliyuncs.com/"+id;
            Map<String,Object> params=new HashMap<String,Object>();
            params.putAll(map1);
            params.putAll(map2);
            params.put("staffPhoto",staffPhoto);
            // 填充pdf模板，并输出pdf
            os = response.getOutputStream();
            JasperFillManager.fillReport(ins,params,new JREmptyDataSource());
            os.flush();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
